package com.hc.java.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/6/8 21:51
 */
public class CglibProxyDemo {
    public static void main(String[] args) {
        MyCglibProxy<ActionUserDataServiceImpl> actionUserDataServiceMyCglibProxy = new MyCglibProxy<>();
        ActionUserDataServiceImpl actionUserDataService = (ActionUserDataServiceImpl)
                actionUserDataServiceMyCglibProxy.getProxyInstance(ActionUserDataServiceImpl.class);
        actionUserDataService.addUser();
    }
}

class ActionUserDataServiceImpl {
    public void addUser() {
        System.out.println("实际执行增加用户的操作。。。");
    }
}

class MyCglibProxy<T> implements MethodInterceptor {

    public Object getProxyInstance(Class<T> tClass) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(tClass);
        enhancer.setCallback(this); // 设置毁掉方法为当前类
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("开始执行代理逻辑。。。");
        // 前置处理或其他逻辑
        beforeProxyRun();
        // 调用原始方法（即目标方法）
        Object result = methodProxy.invokeSuper(o, objects);
        // 后置处理或其他逻辑
        afterProxyRun();
        System.out.println("结束执行增代理逻辑");
        return result;
    }

    private void afterProxyRun() {
        System.out.println("代理后：执行一些后续处理操作。。。");
    }

    private void beforeProxyRun() {
        System.out.println("代理前：执行一些预处理操作。。。");
    }
}